﻿using LuDragon.Data.Config;
using System;
using System.Data;
using System.Data.SqlClient;

namespace LuDragon.Data.DataHandler
{
    public class DapperContext
    {
        /// <summary>
        /// 读取数据库上下文
        /// </summary>
        public static IDbConnection ReadDbContext
        {
            get
            {
                IDbConnection dbConnection;
                if (!string.IsNullOrEmpty(AppConfig.ReadDbContext))
                    dbConnection = new SqlConnection(AppConfig.ReadDbContext);
                else
                {
                    throw new ArgumentNullException("配置文件中无读数据库连接【ReadDbContext】配置！", "ReadDbContext");
                }

                var isClosed = dbConnection.State == ConnectionState.Closed;
                if (isClosed) dbConnection.Open();
                return dbConnection;
            }
        }

        /// <summary>
        /// 写数据库上下文
        /// </summary>
        public static IDbConnection WriteDbContext
        {
            get
            {
                IDbConnection dbConnection;
                if (!string.IsNullOrEmpty(AppConfig.WriteDbContext))
                    dbConnection = new SqlConnection(AppConfig.WriteDbContext);
                else
                {
                    throw new ArgumentNullException("配置文件中无写数据库连接【WriteDbContext】配置！", "writeDbContext");
                }

                var isClosed = dbConnection.State == ConnectionState.Closed;
                if (isClosed) dbConnection.Open();
                return dbConnection;
            }
        }
    }
}